package com.demo.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.domain.SysUser;
import com.demo.domain.SysUserRole;
import com.demo.model.R;
import com.demo.service.SysUserRoleService;
import com.demo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("/users")
public class SysUserController {


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 分页查询用户 数据
     * 涉及表:sys_user
     * @param page
     * @param mobile
     * @param fullname
     * @return
     */
    @GetMapping
    public R<Page<SysUser>> findByPage( Page<SysUser> page,String mobile,String fullname){
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysUser> userPage = sysUserService.findByPage(page,mobile,fullname);
        return R.ok(userPage);
    }

    /**
     * 新增 员工
     * @return
     */
    @PostMapping
    public R addUser(@RequestBody SysUser sysUser){
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        sysUser.setCreateBy(Long.valueOf(userId));
        boolean isOK = sysUserService.addUser(sysUser);

        if (isOK){
            return R.ok();
        }
        return R.fail("新增失败");
    }



    /**
     * 修改 员工 信息
     * @return
     */
    @PatchMapping
    @Transactional
    public R updateUser(@RequestBody SysUser sysUser){


        boolean updateBool = sysUserService.updateUser(sysUser);
        if (updateBool){
            return R.ok();
        }
        return R.fail("修改失败");
    }

    /**
     * 删除 员工 信息
     * @return
     */
    @PatchMapping("/delete")
    @Transactional
    public R deleteUser(@RequestBody Long ids[]){
        boolean removeBatch = sysUserService.removeByIds(Arrays.asList(ids));

        if(removeBatch){
            R.ok();
        }
        return R.fail("修改失败");
    }
}
